﻿using Dapper;
using System;
using BCEntity.Common.DictionaryCategory;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;
using BCCommon.Extensions;
using BCCommon.Enums;

namespace BCData.Common.DictionaryCategory
{
    /// <summary>
    /// 字典分类
    /// </summary>
    public class DictionaryCategoryData : IDictionaryCategoryData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM dictionarycategory";
        private const string QUERY = @"SELECT DictionaryCategoryId,CreateAdminId,CreateAdminName,UpdateTime,EditAdminId,EditAdminName,CategoryCode,CategoryName,CategoryIcon,
                                            ParentDictionaryCategoryId,CategoryLevel,SystemType,TreeCode,CreateTime 
                                        FROM dictionarycategory";
        public DictionaryCategoryData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查字典分类是否存在
        public async Task<bool> Exists(long dictionaryCategoryId)
        {
            string sql = string.Format(@"{0} WHERE DictionaryCategoryId=?DictionaryCategoryId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?DictionaryCategoryId", dictionaryCategoryId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        public async Task<bool> Exists(string categoryCode)
        {
            string sql = string.Format(@"{0} WHERE CategoryCode=?CategoryCode", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CategoryCode", categoryCode, DbType.AnsiString, size: 200);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加字典分类
        public async Task<DictionaryCategoryEntity> Add(DictionaryCategoryEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("dictionarycategory", new string[] { "CreateAdminId", "CreateAdminName", "CategoryCode", "CategoryName", "CategoryIcon",
                "CategoryLevel", "SystemType", "TreeCode" ,"ParentDictionaryCategoryId"});
            sql = string.Format("{0} {1} WHERE DictionaryCategoryId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CreateAdminId", entity.CreateAdminId, DbType.Int64, size: 20);
            parameters.Add("?CreateAdminName", entity.CreateAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CategoryCode", entity.CategoryCode?.Trim(), DbType.AnsiString, size: 200);
            parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 30);
            parameters.Add("?CategoryIcon", entity.CategoryIcon?.Trim(), DbType.AnsiString, size: 1000);
            parameters.Add("?CategoryLevel", entity.CategoryLevel, DbType.Int32, size: 11);
            parameters.Add("?SystemType", entity.SystemType.ToString(), DbType.AnsiString, size: 30);
            parameters.Add("?TreeCode", entity.TreeCode?.Trim(), DbType.AnsiString, size: 1000);
            parameters.Add("?ParentDictionaryCategoryId", entity.ParentDictionaryCategoryId, DbType.Int64, size: 20);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<DictionaryCategoryEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改字典分类
        public async Task<DictionaryCategoryEntity> Update(DictionaryCategoryEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("dictionarycategory", new string[] {"UpdateTime", "EditAdminId", "EditAdminName",
                "CategoryCode", "CategoryName", "CategoryIcon", "ParentDictionaryCategoryId", "CategoryLevel", "SystemType", "TreeCode" }, new string[] { "DictionaryCategoryId" });
            sql = string.Format("{0} {1} WHERE DictionaryCategoryId=?DictionaryCategoryId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?DictionaryCategoryId", entity.DictionaryCategoryId, DbType.Int64, size: 20);
            parameters.Add("?UpdateTime", DateTime.Now, DbType.DateTime);
            parameters.Add("?EditAdminId", entity.EditAdminId, DbType.Int64, size: 20);
            parameters.Add("?EditAdminName", entity.EditAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?CategoryCode", entity.CategoryCode?.Trim(), DbType.AnsiString, size: 200);
            parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 30);
            parameters.Add("?CategoryIcon", entity.CategoryIcon?.Trim(), DbType.AnsiString, size: 1000);
            parameters.Add("?ParentDictionaryCategoryId", entity.ParentDictionaryCategoryId, DbType.Int64, size: 20);
            parameters.Add("?CategoryLevel", entity.CategoryLevel, DbType.Int32, size: 11);
            parameters.Add("?SystemType", entity.SystemType.ToString(), DbType.AnsiString, size: 30);
            parameters.Add("?TreeCode", entity.TreeCode?.Trim(), DbType.AnsiString, size: 1000);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<DictionaryCategoryEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 更新树形码
        public async Task<DictionaryCategoryEntity> UpdateTreeCode(long dictionaryCategoryId, string treeCode)
        {
            string sql = SqlCommands.GetUpdateSql("dictionarycategory", new string[] {"UpdateTime", "EditAdminId", "EditAdminName",
                "CategoryCode", "CategoryName", "CategoryIcon", "ParentDictionaryCategoryId", "CategoryLevel", "SystemType", "TreeCode" }, new string[] { "DictionaryCategoryId" });
            sql = string.Format("{0} {1} WHERE DictionaryCategoryId=?DictionaryCategoryId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?DictionaryCategoryId", dictionaryCategoryId, DbType.Int64, size: 20);
            parameters.Add("?TreeCode", treeCode?.Trim(), DbType.AnsiString, size: 1000);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<DictionaryCategoryEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除字典分类
        public async Task<bool> Delete(long dictionaryCategoryId)
        {
            string sql = @"DELETE FROM dictionarycategory WHERE DictionaryCategoryId=?DictionaryCategoryId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?DictionaryCategoryId", dictionaryCategoryId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取字典分类
        public async Task<DictionaryCategoryEntity> GetEntity(long dictionaryCategoryId)
        {
            string sql = string.Format(@"{0} WHERE DictionaryCategoryId=?DictionaryCategoryId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?DictionaryCategoryId", dictionaryCategoryId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<DictionaryCategoryEntity>(sql, parameters);
        }
        #endregion

        #region 获取字典分类列表
        public async Task<IEnumerable<DictionaryCategoryEntity>> GetList(long? parentCategoryId)
        {
            if (parentCategoryId.HasValue)
            {
                string sql = string.Format(@"{0} WHERE ParentDictionaryCategoryId=?ParentDictionaryCategoryId", QUERY);
                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("?ParentDictionaryCategoryId", parentCategoryId, DbType.Int64);
                return await this.databaseContext.Slave.QueryAsync<DictionaryCategoryEntity>(sql, parameters);
            }
            else
            {
                string sql = string.Format(@"{0} WHERE ParentDictionaryCategoryId IS NULL", QUERY);
                return await this.databaseContext.Slave.QueryAsync<DictionaryCategoryEntity>(sql);
            }
        }
        public async Task<IEnumerable<DictionaryCategoryEntity>> GetList(BCSystemType systemType)
        {
            string sql = string.Format(@"{0} WHERE SystemType=?SystemType ORDER BY TreeCode ASC", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SystemType", systemType.ToString(), DbType.AnsiString);
            return await this.databaseContext.Slave.QueryAsync<DictionaryCategoryEntity>(sql, parameters);
        }
        #endregion

        #region 获取字典分类分页
        public async Task<(IEnumerable<DictionaryCategoryEntity>, int)> Query(DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();

            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM dictionarycategory {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<DictionaryCategoryEntity, int>(sql, parameters);
        }
        #endregion
    }
}



